
package com.feib.soeasy.log4j;

import java.util.Date;

import javax.mail.Multipart;
import javax.mail.Transport;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;

import org.apache.log4j.Layout;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.net.SMTPAppender;
import org.apache.log4j.spi.LoggingEvent;


/**
 * @title (#)SMTPUTF8Appender.java<br>
 * @description <br>
 * @author Jimmy Liu<br>
 * @version 1.0.0 2010/11/25
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2011/1/24 create by Jimmy Liu<br>
 */
public class SMTPUTF8Appender extends SMTPAppender {
    
    /* (non-Javadoc)
     * @see org.apache.log4j.net.SMTPAppender#sendBuffer()
     */
    @Override
    protected void sendBuffer() {

        // Note: this code already owns the monitor for this
        // appender. This frees us from needing to synchronize on 'cb'.
        try {
          MimeBodyPart part = new MimeBodyPart();

          StringBuffer sbuf = new StringBuffer();
          String t = layout.getHeader();
          if(t != null)
            sbuf.append(t);
          int len =  cb.length();
          for(int i = 0; i < len; i++) {
            //sbuf.append(MimeUtility.encodeText(layout.format(cb.get())));
            LoggingEvent event = cb.get();
            sbuf.append(layout.format(event));
            if(layout.ignoresThrowable()) {
              String[] s = event.getThrowableStrRep();
              if (s != null) {
                for(int j = 0; j < s.length; j++) {
                  sbuf.append(s[j]);
                  sbuf.append(Layout.LINE_SEP);
                }
              }
            }
          }
          t = layout.getFooter();
          if(t != null)
            sbuf.append(t);
          //part.setContent(sbuf.toString(), layout.getContentType());
          part.setContent(sbuf.toString(), "text/plain;charset=UTF-8");

          Multipart mp = new MimeMultipart();
          mp.addBodyPart(part);
          msg.setContent(mp);

          msg.setSentDate(new Date());
          Transport.send(msg);
        } catch(Exception e) {
          LogLog.error("Error occured while sending e-mail notification.", e);
        }
    }

}
